import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 朋友列表视图模型
/// 管理朋友列表页面的数据和状态
class FriendsListViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final RelationBond _relationBond;
  final DialogLens _dialogLens;

  FriendsListViewModel(this._authFocus, this._relationBond, this._dialogLens);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  List<UserFrame> _friends = [];
  List<UserFrame> get friends => _friends;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      if (_currentUser == null) {
        setBusy(false);
        return;
      }

      await _loadFriends();
    } finally {
      setBusy(false);
    }
  }

  /// 加载朋友列表
  Future<void> _loadFriends() async {
    if (_currentUser == null) return;

    final friendIds = await _relationBond.getFriendsList(_currentUser!.id);
    final allUsers = await _authFocus.getUsers();

    _friends = allUsers.where((user) => friendIds.contains(user.id)).toList();
    notifyListeners();
  }

  /// 取消关注用户（删除朋友）
  Future<void> unfollowFriend(String friendId) async {
    if (_currentUser == null) return;

    await _relationBond.unfollowUser(
      followerId: _currentUser!.id,
      followingId: friendId,
    );

    await _loadFriends();
  }

  /// 检查是否有与用户的对话
  Future<bool> hasChatWithUser(String userId) async {
    if (_currentUser == null) return false;

    final messages = await _dialogLens.getChatMessages(
      userId1: _currentUser!.id,
      userId2: userId,
    );

    return messages.isNotEmpty;
  }

  /// 创建对话（发送一条初始消息）
  Future<void> createChatWithUser(String userId) async {
    if (_currentUser == null) return;

    await _dialogLens.sendTextMessage(
      senderId: _currentUser!.id,
      receiverId: userId,
      content: 'Hello!',
    );
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }
}
